package ink.zhaohui.book.service.impl;

import java.util.ArrayList;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ink.zhaohui.book.bo.BookBO;
import ink.zhaohui.book.dao.IBookDAO;
import ink.zhaohui.book.service.IBookService;
import ink.zhaohui.book.tool.Helper;
import ink.zhaohui.book.vo.BookVO;
import ink.zhaohui.book.vo.Page;

@Component
public class BookService implements IBookService {

	private IBookDAO bookDAO;

	@Autowired
	public BookService(IBookDAO bookDAO) {
		this.bookDAO = bookDAO;
	}

	@Override
	public BookVO queryOneByUuid(String uuid) {
		// TODO Auto-generated method stub
		return Helper.bookBO2BookVO(bookDAO.queryOne(uuid, null));
	}

	@Override
	public BookVO queryOneByOrderUuid(String orderUuid) {
		// TODO Auto-generated method stub
		return Helper.bookBO2BookVO(bookDAO.queryOne(null, orderUuid));
	}

	@Override
	public Page<BookVO> queryMore(String name, int pageSize, int at) {
		// TODO Auto-generated method stub
		Page<BookBO> p=bookDAO.queryMore(name, pageSize, at);
		Page<BookVO> v=new Page();
		v.atPage=p.atPage;
		v.pageSize=p.pageSize;
		v.totalPage=p.totalPage;
		v.data=new ArrayList<BookVO>();
		for(int n=0;n<p.data.size();n++)
		{
			v.data.add(Helper.bookBO2BookVO(p.data.get(n)));
		}
		return v;
	}

	@Override
	public BookVO bookOne(BookVO bookVO) {
		// TODO Auto-generated method stub
		bookVO.setUuid(UUID.randomUUID().toString().replace("-", ""));
		BookBO bookBO=Helper.bookVO2BookBO(bookVO);
		bookBO=bookDAO.create(bookBO);
		bookVO.setId(bookBO.getId());
		return bookVO;
	}

	@Override
	public int cancelBook(String uuid) {
		// TODO Auto-generated method stub
		return changeBookState(uuid, BookVO.State.ORDER_CANCEL);
	}

	protected int changeBookState(String uuid, BookVO.State state) {
		BookBO b = new BookBO();
		b.setUuid(uuid);
		b.setStateCode(state.getCode());
		return bookDAO.updateByUuid(b);
	}

	@Override
	public int finishBook(String uuid) {
		// TODO Auto-generated method stub
		return changeBookState(uuid, BookVO.State.FINISH);
	}

	@Override
	public int cancelFinishBook(String uuid) {
		// TODO Auto-generated method stub
		return changeBookState(uuid, BookVO.State.FINISH_CANCEL);
	}

}
